package com.yimingkeji.jdbc.rest;

import com.yimingkeji.jdbc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/12/3 16:08
 */
@RestController
@RequestMapping("/user")
public class UserResource {

    @Autowired private JdbcTemplate jdbcTemplate;

    @GetMapping("")
    public List list(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from user");
        return list;
    }

    @PostMapping("")
    public User add(@RequestBody User user){
        String sql = "insert into user(name,age) values(?, ?)";
        jdbcTemplate.update(connection -> {
            PreparedStatement ps= connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1,user.getName());
            ps.setInt(2,user.getAge());
            return ps;
        });
        return user;
    }
}
